<template>
  <view class="page">
    <map
      class="map"
      :markers="location.markers"
      :include-points="includePoints"
      @markertap="onMarkertap"
    ></map>

    <view class="button-box">
      <button class="button" @click="go('/pages/publish/publish')">发布</button>
      <button class="button" @click="go('/pages/search/search')">搜索</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, computed } from "vue";
import { onLoad, onPullDownRefresh } from "@dcloudio/uni-app";
import { useUserStore } from "@/stores/user";

interface ITrade {
  id: number;
  openid: string;
  lat: string;
  lng: string;
  address: string;
  message: string;
  contact: string;
  type: string;
}

const userStore = useUserStore();

// 定位数据
const location = reactive({
  // latitude: 0,
  // longitude: 0,
  markers: [] as any[],

  includePoints: [] as any[],
});

const includePoints = computed(() => {
  return location.markers.map((item) => ({
    latitude: item.latitude,
    longitude: item.longitude,
  }));
});

/**
 * 获取交易列表数据
 */
const getList = (): Promise<ITrade[]> => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: "http://localhost:3000/trades",
      method: "GET",
      success: (res: any) => {
        resolve(res.data);
      },
      fail: (error) => {
        reject(error);
      },
    });
  });
};

/**
 * 获取用户的地理定位
 */
const getLocation = (): Promise<{
  latitude: string;
  longitude: string;
}> => {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: "gcj02",
      success: (res: any) => {
        resolve(res);
      },
      fail: (error) => {
        reject(error);
      },
    });
  });
};

const go = (pagePath: string) => {
  uni.navigateTo({
    url: pagePath,
    success: (res) => {
      // 通过页面间的通道来监听一个 refresh 事件
      res.eventChannel.once("refresh", () => {
        console.log("refresh");
        // 获取新数据
        getList().then((list) => {
          // 将 list => location.markers
          location.markers = list.map((item) => ({
            id: item.id,
            latitude: item.lat,
            longitude: item.lng,
            iconPath: `../../static/icon-${item.type}.png`,
            width: 40,
            height: 40,
          }));
        });
      });
    },
  });
};

// 标注点点击
const onMarkertap = (event: any) => {
  // console.log("onMarkertap", event);
  // 获取标记点的Id,也就是交易数据的Id
  const { markerId } = event.detail;

  // 跳转页面
  uni.navigateTo({
    url: `/pages/info/info?id=${markerId}`,
  });
};

onLoad(async () => {
  Promise.all([userStore.getLocation(), getList()]).then(([loc, list]) => {
    console.log("loc", loc);
    // location.latitude = loc.latitude;
    // location.longitude = loc.longitude;

    // 将 list => location.markers
    location.markers = list.map((item) => ({
      id: item.id,
      latitude: item.lat,
      longitude: item.lng,
      iconPath: `../../static/icon-${item.type}.png`,
      width: 40,
      height: 40,
    }));

    location.includePoints = list.map((item) => ({
      latitude: item.lat,
      longitude: item.lng,
    }));
  });

  // 两个异步代码没有依赖关系的话，不要去使用 await await
  //  考虑（串行与并行）
  // await getLocation();
  // const resp = await getList();
  // console.log("resp", resp);
});
</script>

<style scoped>
.page {
  height: 100%;
}

.map {
  width: 100%;
  height: 100%;
}

.button-box {
  position: fixed;
  left: 0;
  bottom: 0;
  padding-bottom: env(safe-area-inset-bottom);
  display: flex;
  width: 100%;
  background-color: #fff;
}

.button {
  flex: 1;
}
</style>
